using System;
using System.IO;
using System.Collections;

namespace TuMama
{
	/// <summary>
	/// Summary description for INPClient.
	/// </summary>
	public class GestorConexionCliente : ClientBase
	{
        private Mensaje ultimo;

        public event EventHandler RecieveCompleted;
        private ArrayList bytesInBuffer = new ArrayList();

		public GestorConexionCliente(string serverIP,int port) : base(serverIP,port)
		{
            this.ultimo = new Mensaje(null, Mensaje.tipoObjeto.NULL, Mensaje.message.poll);

		}

        public void OnRecieveCompleted()
        {
            if (RecieveCompleted != null)
                RecieveCompleted(this, new EventArgs());
        }


         
        public override void OnDataRecieved(ClientInfo info)
        {
            // change the fileName if you want to test this whit a other file.
            //Byte [] aux = new Byte [(bytesInBuffer.Length+1024)];


            foreach (Byte miByte in info.Buffer)
            {
                this.bytesInBuffer.Add(miByte);
            }


            //FileStream fs = new FileStream("test.jpg",FileMode.Append);
            //fs.Write(info.Buffer,0,info.Buffer.Length);

            //fs.Flush();

            //// this is importend
            //// don't forget to close the file or you won't be able to acces
            //// the file the next time the function is called.
            //fs.Close();

            //// check if the stream is empty
            if (info.Socket.Available == 0)
            {
                try
                {
                    byte[] aux = new Byte[(this.bytesInBuffer.Count)];
                    this.bytesInBuffer.CopyTo(aux);
                    //String ruta = Environment.CurrentDirectory;
                    //String path = Path.Combine(ruta, "");
                    //String file = "waga.mp3";
                    //FileStream fs = new FileStream(Path.Combine(path, file), FileMode.Create);
                    //fs.Write(aux, 0, System.Convert.ToInt32(aux.Length));
                    //fs.Seek(0, SeekOrigin.Begin);
                    //fs.Close();
                    ultimo = ByteMensaje.GetMensajeObject(aux);
                    this.bytesInBuffer = new ArrayList();
                    OnRecieveCompleted();
                }
                catch (Exception e)
                {
                    base.OnDataRecieved(info);
                }
            }
            base.OnDataRecieved(info);
        }

		public void SendMessage(Mensaje m)
		{
            byte[] im = ByteMensaje.GetBytes(m);
			base.Send(im);
		}


        public Mensaje getLastReceived()
        {
            return ultimo;
        }
	}
}
